﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.ComponentModel;

namespace giaoxuhaison.Common
{
    public class PageCalculator : IPageCalculator
    {
        private readonly int MaxRowNumbersPerPage = 100000000;
        
        public int GetPositionByRowId<T>(List<T> source, string rowNumber,string rowId)
        {
            if (source != null && source.Any() && rowNumber != string.Empty && rowId != string.Empty)
            {
                int numberRowPerPage = Convert.ToInt16(rowNumber);
                int id = Convert.ToInt16(rowId);
                if (numberRowPerPage >0 && id>0 && numberRowPerPage < MaxRowNumbersPerPage)
                {
                    return CalculatePositionOfPage(source, id, numberRowPerPage);
                }
            }

            return 1;
        }

        private int CalculatePositionOfPage<T>(List<T> source, int id, int numberRowPerPage)
        {
            var index = source.FindIndex(x => (int)x.GetType().GetProperty("Id").GetValue(x, null) == id);
            if (index > 0)
            {
                return (int)Math.Ceiling((index + 1) / (numberRowPerPage * 1.0));
            }

            return 1;
        }
    }
}